package com.zixi.ai.workflow.service.impl;

import com.agentsflex.core.chain.Chain;
import com.alibaba.fastjson2.JSONObject;
import com.zixi.ai.common.exception.ServiceException;
import com.zixi.ai.framework.service.BaseServiceImpl;
import com.zixi.ai.workflow.entity.AiWorkflowEntity;
import com.zixi.ai.workflow.service.IAiWorkflowService;
import com.zixi.ai.workflow.service.ITinyFlowConfigService;
import dev.tinyflow.core.Tinyflow;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Optional;

/**
 * @author wfg
 */
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class AiWorkflowServiceImpl extends BaseServiceImpl<AiWorkflowEntity, Long> implements IAiWorkflowService {
    private final ITinyFlowConfigService tinyFlowConfigService;
    @Override
    public Map<String, Object> tryRunning(Long id, JSONObject variables) {
        Optional<AiWorkflowEntity> workflow = findById(id);
        if (workflow.isEmpty()) {
            throw new ServiceException("工作流不存在");
        }
        String content = workflow.get().getContent();
        if (content == null) {
            throw new ServiceException("工作流未配置不存在");
        }
        Tinyflow tinyflow = new Tinyflow(content);
        initProvidersAndNodeParsers(tinyflow);
        Chain chain = tinyflow.toChain();
//        chain.getMemory().put(Constants.LOGIN_USER_KEY, SaTokenUtil.getLoginAccount());
        return chain.executeForResult(variables);
    }

    private void initProvidersAndNodeParsers(Tinyflow tinyflow) {
        tinyFlowConfigService.setExtraNodeParser(tinyflow);
        tinyFlowConfigService.setSearchEngineProvider(tinyflow);
        tinyFlowConfigService.setLlmProvider(tinyflow);
        tinyFlowConfigService.setKnowledgeProvider(tinyflow);
        tinyFlowConfigService.setFileStorage(tinyflow);
    }
}
